<?php
class gallery_model extends Model {

    var $renderedPages;
    var $galdir;
    var $max_size='4000';
    var $max_width='3000';
    var $max_height='3000';
    var $resize_width=800;
    var $resize_height=600;
    

    function gallery_model()
    {
        // Call the Model constructor
        parent::Model();
        $this->galdir=MEDIA_DIR.'galleries/';
        $this->load->helper('file');
        $this->load->helper('normalize');
    }

    function getAllGals()
    {
        $handle = opendir($this->galdir);
        $dirArr=array();
        while( $newfile = readdir($handle) ) {
            if (is_dir($this->galdir.$newfile) and ($newfile!='.') and ($newfile!='..'))
            $dirArr[]=$newfile;
        }
        return $dirArr;
    }
    
    function addGal($galname)
    {
        if (!$this->galExists($galname)) {
            //create the new directory
            $err=mkdir ($this->galdir.normalizeStr($galname), 0700);
            return ($err and mkdir ($this->galdir.normalizeStr($galname).'/thumbs', 0700));
        } else {
            return false;
        }
            
    }
    
    function delGal($galname)
    {
        if ($this->galExists($galname)) {
            //create the new directory
            delete_files($this->galdir.normalizeStr($galname),true);
            $err=rmdir($this->galdir.normalizeStr($galname).'/thumbs');
            return ($err and rmdir($this->galdir.normalizeStr($galname)));
        } else {
            return false;
        }
    }
    
    function galExists($galname)
    {
        return in_array(normalizeStr($galname),$this->getAllGals());
    }
    
    
    //returns gallery data
    function getGalleryData($galname)
    {
        if ($this->galExists($galname)) {
            //get image files
            $dir=MEDIA_DIR.'galleries/'.$galname.'/';
            $data=array();
            $data['main']['name']=$galname;
            $data['main']['template']='default';
            $data['images']=array();
            $filenames = $this->getFiles($dir,'/\.(jpg|gif|png)$/');
            foreach ($filenames as $filename) {
                $data['images'][$filename]=array( 
                    'order'=>'n',
                    'caption'=>'',
                    'filename'=>$filename,
                    'tags'=>'',
                    'url'=>BASEURL.$dir.$filename,
                    'thumb_url'=>$this->getThumb($dir.$filename)
                    );
            }
            //combine with saved infos
            if (file_exists($dir.'info.dat')) {
                $saved_data=unserialize(read_file($dir.'info.dat'));
                $data['main']=@array_merge($data['main'],$saved_data['main']);
                foreach ($data['images'] as $filename=>$image) {
                    $data['images'][$filename]=@array_merge($data['images'][$filename],@$saved_data['images'][$filename]);
                }
            }
            asort($data['images']);
            return $data;
        } else {
            return false;
        }
    }
    
    //
    function saveGalleryData($galname,$data)
    {
        if ($this->galExists($galname)) {
            //get image giles
            //merge with existing data
            $prevdata=$this->getGalleryData($galname);
            $data['main']=array_merge($prevdata['main'],$data['main']);
            foreach ($prevdata['images'] as $filename=>$image) {
                $data['images'][$filename]=array_merge($prevdata['images'][$filename],$data['images'][$filename]);
            }
            $dir=MEDIA_DIR.'galleries/'.$galname.'/';
            write_file($dir.'info.dat',serialize($data));
            return true;
        } else {
            return false;
        }
    }
    
    
    function delImage($galname,$filename)
    {
        if (file_exists($this->galdir.$galname.'/'.$filename)) {
            unlink($this->galdir.$galname.'/'.$filename);
            unlink($this->galdir.$galname.'/'.'thumbs/thumb_'.$filename);
            return true;
        } else {
            return false;
        }
    }
    
    //do the upload and resizing with the new image
    function addImage($galname)
    {
    		$config['upload_path'] = $this->galdir.$galname;
    		$config['allowed_types'] = 'gif|jpg|png|swf|mp3';
    		$config['max_size']	= $this->max_size;
    		$config['max_width']  = $this->max_width;
        	$config['max_height']  = $this->max_height;
    		
    		$this->load->library('upload', $config);
    	
    		if ( ! $this->upload->do_upload()) {
    		      //error
    			return $this->upload->display_errors();  	
    		} else {
    			$uploadData = $this->upload->data();
    			//print_r($uploadData);
    			$this->load->helper('normalize');
    			$newfilename=normalizeStr($uploadData['raw_name']).strtolower($uploadData['file_ext']);
    			rename($uploadData['full_path'],$uploadData['file_path'].$newfilename);
                if ($uploadData['is_image']) {
                    //resize the image
                    $config['source_image'] = $uploadData['file_path'].$newfilename;
                    $config['width'] = 800;
                    $config['height']= 600;
                    $this->load->library('image_lib');
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
                }  
                return true; 			
    		}
    }
    
    /**
    * Returns the thumbnail url matching the filename 
    * if it doesn't exists, creates it    
    * @param  string $filename
    * @return string thumbnail url
    */
    function getThumb($filename)
    {
        if (file_exists($filename)) {
            $fileinfo = pathinfo($filename);
            $dir=$fileinfo['dirname']."/";
            $images_ext = array ("png","gif","jpg");
            if (in_array($fileinfo['extension'], $images_ext)) {
                $thumbfile=$dir.'thumbs/thumb_'.$fileinfo['basename'];
                if (!file_exists($thumbfile)) {
                    //thumb needs to be created
                    $config['source_image'] = $filename;
                    $config['width'] = 100;
                    $config['height']= 100;
                    $config['new_image'] = $thumbfile;
                    $this->load->library('image_lib');
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
                }
                return BASEURL.$thumbfile;
            }
        }
        return false;
    }  
    
    
    //return an array of all dirs
    function getFiles($dir,$match='/.*/')
    {
        $filesArr = array();
        $handle = opendir($dir);
        while( $newfile = readdir($handle) ) {
            if (!is_dir($newfile) and ($newfile!='.') and ($newfile!='..') and preg_match($match,$newfile))
            $filesArr[]=$newfile;
        }
        return $filesArr;
    }
    

}
?>
